package com.hopu.v1.service.admin.system.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hopu.v1.exception.BusinessException;
import com.hopu.v1.mapper.admin.system.MenuMapper;
import com.hopu.v1.pojo.classes.Student;
import com.hopu.v1.pojo.common.R;
import com.hopu.v1.pojo.system.Menu;
import com.hopu.v1.service.admin.system.MenuService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author YwaiX
 * @since 2024-09-12
 */
@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements MenuService {
    @Resource
    private MenuMapper menuMapper;

    @Override
    public List<Menu> selectByPidAndStatus(Integer pid, Integer status) {
        return menuMapper.selectByPidAndStatus(pid,status);
    }

    /**
     * 菜单添加
     * @param menu
     */
    @Override
    public void insertMenu(Menu menu) {
        LambdaQueryWrapper<Menu> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Menu::getMenuName, menu.getMenuName());
        Menu menu1 = getOne(lambdaQueryWrapper);
        if(menu1!=null){
            throw new BusinessException("菜单名已存在！不能重复");
        }
        save(menu);
    }

    /**
     * 菜单修改
     * @param menu
     */
    @Override
    public R updateMenu(Menu menu) {
        if (checkName(menu)){
            return R.err(500,"该菜单名已存在！");
        }
        if (checkUrl(menu)){
            return  R.err(500,"该菜单跳转地址已存在！");
        }
        menu.setUpdateTime(LocalDateTime.now());
        return R.ok("修改成功！",updateById(menu));
    }

    /**
     * 菜单名称查重
     * @param menu
     */
    @Override
    public boolean checkName(Menu menu) {
        List<Menu> list = list(new LambdaQueryWrapper<Menu>().eq(Menu::getMenuName, menu.getMenuName()));
        if (list == null){
            return false;
        }
        for (Menu value : list) {
            if (Objects.equals(value.getId(), menu.getId())) {
                return false;
            }
        }
        return true;
    }

    /**
     * url查重
     * @param menu
     * @return
     */
    @Override
    public boolean checkUrl(Menu menu) {
        if (Objects.equals(menu.getUrl(), "/")){
            return false;
        }
        List<Menu> menus = menuMapper.selectList(new LambdaQueryWrapper<Menu>().eq(Menu::getUrl, menu.getUrl()));
        for (Menu value : menus) {
            if (Objects.equals(value.getId(), menu.getId())) {
                return false;
            }
        }
        return menus != null && !menus.isEmpty();
    }


}
